<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/15 0015
 * Time: 16:28
 */

namespace Admin\Controller;


use Think\Controller;

class CategoryController extends Controller
{
    public function lst()
    {
        $model = D('category');
        $data = $model->getTree();
        $this->assign(array(
            "data" => $data,
            '_page_title' => '分类列表',
            '_page_btn_name' => '添加分类',
            '_page_btn_link' => U('add'),
        ));
        $this->display();
    }

    public function edit()
    {
        $id = I('get.id');
        $model = D('category');
        if (IS_POST) {
            /**
             * creatr() 2个参数
             * 1 接受的参数
             * 2 表单的类型 1添加 2修改
             */
            if ($model->create(I('post.'), 1)) {
                if ($model->save()) {
                    $this->success('操作成功', U('lst'));
                    exit;
                }
            }
            $error = $model->getError();
            $this->error($error);
        }
        $data = $model->getTree();
        $childs=$model->getChildren($id);
        $model->where(array());
        $this->assign(array(
            "data" => $data,
            'id' => $id,
            'childs' => $childs,

        ));
        $this->display();
    }

    public function add()
    {
        $model = D('category');
        if (IS_POST) {
            /**
             * creatr() 2个参数
             * 1 接受的参数
             * 2 表单的类型 1添加 2修改
             */
            if ($model->create(I('post.'), 1)) {
                if ($model->add()) {
                    $this->success('操作成功', U('lst'));
                    exit;
                }
            }
            $error = $model->getError();
            $this->error($error);
        }
        $data = $model->getTree();
        $this->assign(array(
            "data" => $data,
        ));
        $this->display();
    }

    public function delete()
    {
        $id = I('get.id');
        $model = D('category');
        $childs = $model->getChildren($id);
        $childs[] = $id;
        $res = $model->where(array(
            'id' => array('in',implode(",", $childs)),
        ))->delete();
        if ($res && $res > 0) {
            $this->success('操作成功', U('lst'));
        } else {
            $error = $model->getError();
            $this->error($error);
        }
    }

}